<template>
  <el-autocomplete
    class="inline-input"
    v-model="searchInput"
    :fetch-suggestions="querySearch"
    :placeholder="$language.local('请输入内容')"
    :trigger-on-focus="false"
    clearable
    @clear="onClearProc"
    @select="handleSelect"
    v-loadmore="loadMore"
  >
    <!-- <el-select
              size="small"
              v-model="queryAttribute"
              slot="prepend"
              placeholder="请选择"
              @change="queryAttributeChange"
            >
              <el-option
                v-for="(item, key) in columns"
                :key="key"
                :label="$language.local(key)"
                :value="key"
              >
              </el-option>
            </el-select> -->
    <template slot="append">
      <slot name="append"> </slot>
    </template>
  </el-autocomplete>
</template>

<script>
export default {
  props: {
    value: String,
    apiName: String,
    queryColumn: String,
    columns: Object,
  },
  data() {
    return {
      searchInput: this.value,
      queryInfo: {
        keywords: "",
        pageSize: 8,
        page: 1,
      },
      total: 0,
      results: [],
    };
  },
  computed: {
    queryKey() {
      if (this.queryColumn) {
        return this.queryColumn;
      } else {
        const keys = Object.keys(this.columns);
        return keys[0];
      }
    },
    maxPage: function () {
      return Math.ceil(this.total / this.queryInfo.pageSize);
    },
  },
  methods: {
    async querySearch(queryString, cb) {
      console.log(queryString);
      this.$emit("input", queryString);
      if (queryString) {
        this.queryInfo.keywords = queryString;
        let response = await this.$http.get(this.apiName, this.queryInfo);
        console.log(response);
        this.total = response.TotalCount;
        this.results = this.results.concat(response.data.Data);
      }
      this.results.forEach((v) => {
        v.value = v[this.queryKey];
      });
      // 调用 callback 返回建议列表的数据
      cb(this.results);
    },
    onClearProc() {
      this.queryInfo.keywords = null;
      this.$emit("clear");
      // this.getData();
    },
    queryAttributeChange(item) {
      // this.queryInfo.queryAttribute = item.replace(
      //   item[0],
      //   item[0].toUpperCase()
      // );
      console.log(item);
    },
    handleSelect(item) {
      // this.dataList = [item];
      this.$emit("select", [item]);
    },
    async loadMore() {
      if (this.queryInfo.page >= this.maxPage) {
        return;
      }
      this.queryInfo.page++;
      await this.getOptions();
    },
  },
};
</script>

<style></style>
